package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.NumberConstant;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.controller.base.BaseController;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.service.PhotoAlbumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商城相册表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-27
 */
@RestController
@Api(tags = "商城相册表 相关接口")
@RequestMapping("/commodity/photo/album")
public class PhotoAlbumController extends BaseController {

    @Autowired
    private PhotoAlbumService photoAlbumService;


    @ApiOperation(value = "新增数据", notes = "新增一条商城相册表数据")
    @PostMapping("/add")
    public ResponseResult add(@Validated @RequestBody PhotoAlbumVO photoAlbum, @RequestHeader(RequestConstant.ADMIN_NAME) String username) {
        PhotoAlbumDTO dto = vo2Dto(photoAlbum);
        dto.setCreater(username);
        dto.setModifier(username);
        photoAlbumService.insert(dto);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "删除数据", notes = "删除指定ID商城相册表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestParam Integer id) {
        photoAlbumService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID商城相册表数据")
    @PutMapping("/update")
    public ResponseResult<PhotoAlbumDO> update(PhotoAlbumDO photoAlbum) {
        photoAlbum.setUpdateTime(LocalDateTime.now());
        photoAlbumService.updateById(photoAlbum);
        return ResultGenerator.genSuccessResult(photoAlbum);
    }


    @ApiOperation(value = "查询数据", notes = "获取指定ID商城相册表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<PhotoAlbumDO> detail(@RequestParam Integer id) {
        PhotoAlbumDO photoAlbum = photoAlbumService.getById(id);
        return ResultGenerator.genSuccessResult(photoAlbum);
    }


    @ApiOperation(value = "查询分页", notes = "获取商城相册表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            PhotoAlbumVO photoAlbum) {
        LambdaQueryWrapper<PhotoAlbumDO> wrapper = Wrappers.lambdaQuery();
        if(StatusEnum.STATUS_YES.getCode()==photoAlbum.getOrderType()){
            wrapper.orderByAsc(PhotoAlbumDO::getOrderNum);
        }else{
            wrapper.orderByDesc(PhotoAlbumDO::getOrderNum);
        }
        IPage<PhotoAlbumDO> pageInfo = photoAlbumService.page(
                new Page<>(page, size),wrapper);
        List<ImageSpaceDO> images = photoAlbumService.selectCountByaAlnumID(
                pageInfo.getRecords().stream().map(p->{
                    return p.getId();
                }).collect(Collectors.toList()));
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords(),photoAlbum.getOrderType(),images),pageInfo.getTotal());
    }

    @ApiOperation(value = "获取相册下拉列表", notes = "获取相册下拉列表")
    @GetMapping("/listDrop")
    public ResponseResult listDrop() {
        List<PhotoAlbumDO> list = photoAlbumService.list(
                Wrappers.<PhotoAlbumDO>lambdaQuery()
                        .orderByDesc(PhotoAlbumDO::getUpdateTime));
        return ResultGenerator.genSuccessResult(pos2Vos(list,null,null));
    }

    /**
     * vo->dto
     * @param vo
     * @return
     */
    private PhotoAlbumDTO vo2Dto(PhotoAlbumVO vo){
        PhotoAlbumDTO dto = null;
        try {
            dto = vo.clone(PhotoAlbumDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dto;
    }

    /**
     * 列表对象转换
     * @param pos
     * @return
     */
    private List<PhotoAlbumVO> pos2Vos(List<PhotoAlbumDO> pos, Integer orderType, List<ImageSpaceDO> images){
        return pos.stream().map(p->{
            PhotoAlbumVO vo = null;
            try {
                vo = p.clone(PhotoAlbumVO.class);
                //返给前端顺序
                vo.setOrderType(orderType);
                ImageSpaceDO im = images.stream().filter(d->p.getId().equals(d.getPhotoAlbumId())).findAny().orElse(null);
                vo.setImageNum(im!=null?im.getImageSize(): NumberConstant.NUMBER_ZERO.intValue());
                vo.setPhotoAlbumCover(im.getImageCover());
            }catch (Exception e){
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
    }

}
